import pymysql as mysql

# 全局变量声明
connection = None

def get_db_config():
    """获取数据库配置"""
    return {
        'user': 'root',
        'password': '123456',
        'host': '1.94.107.109',
        'database': 'pomonitor'
    }

def connect_mysql():
    # 连接数据库
    global connection
    if connection is not None:
        return connection, connection.cursor()

    try:
        config = get_db_config()
        connection = mysql.connect(**config)
        print("连接成功")
        cursor = connection.cursor()
        return cursor, connection
    except Exception as e:
        print(f"连接失败: {str(e)}")
        raise e




def query_data(data,cursor):
    #查询操作
    query = "SELECT * FROM apl_list_info"
    cursor.execute(query)
    results = cursor.fetchall()
    for row in results:
        print(row)
def save_data(table,data,table_columns):
    cursor,connect  =connect_mysql()
    columns = ""
    columns_data = ""
    add_query = ""
    #插入操作
    for prop in data:
        if prop in table_columns:
            columns = columns + prop + ","
            columns_data = columns_data + str(data[prop]) + "','"
    add_query = " insert into " + table + "(" + columns[0:-1] + ")" + " values " + "('" + columns_data[0:-2] + ")"

    # data = ("value1", "value2")
    # cursor.execute(add_query, data)
    print(add_query)
    cursor.execute(add_query)
    connect.commit()

# 更新操作
# update_query = "UPDATE your_table SET column1 = %s WHERE column2 = %s"
# update_data = ("updated_value1", "value2")
# cursor.execute(update_query, update_data)
# connection.commit()

# 删除操作
# delete_query = "DELETE FROM your_table WHERE column1 = %s"
# delete_data = ("value1",)
# cursor.execute(delete_query, delete_data)
# connection.commit()

# 关闭数据库连接
def close_mysql(cursor,connection):
    cursor.close()
    connection.close()


connect_mysql()
# cursor.close()
# connection.close()